<template>
  <div>
    <myDivider :name="scene == 'add' ? '新增过户信息' : '修改过户信息'"></myDivider>
    <el-page-header @back="$router.push('/Transfer/TransferList')">
    </el-page-header>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" style="width: 1000px;margin: 20px 0 0 20px;"
      label-width="100px">
      <el-row :gutter="40">
        <!-- 原业主信息  原业主信息  原业主信息  原业主信息-->
        <el-col :span="12">
          <div style="display: flex;margin: 20px 0;align-items: center;">
            <i class="el-icon-s-custom" style="font-size: 26px;margin-right:15px ;"></i>
            <span>原业主信息</span>
          </div>
          <el-form-item label="房间信息：" prop="customerOldOwner.roomIdsArray">
            <div style="display: flex;">
               <myCascader v-if="myCascaderShow" :defaultVal="defaultVal" :props="props" @getData="myCascaderGetData">
                          </myCascader>
            </div>
          </el-form-item>
          <el-form-item label="业主信息：" prop="customerOldOwner.customerName">
            <div style="display: flex;">
              <el-input disabled placeholder="请选择业主" style="flex: 1;"
                :value="ruleForm.customerOldOwner.customerName"></el-input>
              <el-button style="margin-left: 10px;" type="primary" @click="choiceUser('Old')">选择</el-button>
            </div>
          </el-form-item>
          <el-form-item label="业主电话：" prop="customerOldOwner.phone">
            <el-input style="flex: 1;" disabled placeholder="请输入" v-model="ruleForm.customerOldOwner.phone"></el-input>
          </el-form-item>
          <el-form-item label="身份证号：" prop="customerOldOwner.idNumber">
            <el-input style="flex: 1;" disabled placeholder="请输入" maxlength="18"
              v-model="ruleForm.customerOldOwner.idNumber"></el-input>
          </el-form-item>
        </el-col>
        <!-- 新业主信息  新业主信息  新业主信息  新业主信息-->
        <el-col :span="12">
          <div style="display: flex;margin: 20px 0;align-items: center;">
            <i class="el-icon-s-custom" style="font-size: 26px;margin-right:15px ;"></i>
            <span>新业主信息</span>
          </div>
          <el-form-item label="房屋归属：" prop="customerNewOwner.ownership">
            <el-select style="width: 100%;" v-model="ruleForm.customerNewOwner.ownership" placeholder="请选择房屋归属">
              <el-option :label="item.name" v-for="item, i in housesData" :key="i" :value="item.value * 1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业主信息：" prop="customerNewOwner.customerName">
            <div style="display: flex;">
              <el-input disabled placeholder="请选择业主" style="flex: 1;"
                :value="ruleForm.customerNewOwner.customerName"></el-input>
              <el-button style="margin-left: 10px;" type="primary" @click="choiceUser('New')">选择</el-button>
            </div>
          </el-form-item>
          <el-form-item label="业主电话：" prop="customerNewOwner.phone">
            <el-input style="flex: 1;" disabled placeholder="请输入" v-model="ruleForm.customerNewOwner.phone"></el-input>
          </el-form-item>
          <el-form-item label="身份证号：" prop="customerNewOwner.idNumber">
            <el-input style="flex: 1;" disabled placeholder="请输入" maxlength="18"
              v-model="ruleForm.customerNewOwner.idNumber"></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 附件 -->
      <!-- 附件 -->
      <!-- 附件 -->
      <div style="display: flex;margin: 50px 0 20px 0;align-items: center;">
        <i class="el-icon-upload" style="font-size: 26px;margin-right:15px ;"></i>
        <span>附件</span>
      </div>
      <el-form-item label="图片：">
        <MyUploadImgNotDetele v-if="MyUploadImgNotDeteleShow" :canUploadNum="5" @deleteImgList="deleteImgList"
          @getImgList="getImgList" :id="uploadId" :EchoImgList="EchoImgList"
          uploadUrl="/business/transferOwnership/uploadImg"></MyUploadImgNotDetele>
      </el-form-item>

      <el-form-item label="附件：">
        <MyUploadFileNotDetele v-if="MyUploadFileNotDeteleShow" @deleteFileList="deleteFileList"
          @getFileList="getFileList" :id="uploadId" :EchoFileList="EchoFileList"
          uploadUrl="/business/transferOwnership/uploadAnnex">
        </MyUploadFileNotDetele>
      </el-form-item>
      <el-form-item label="经办人：" prop="" required>
        <el-input disabled style="width: 200px;" v-model="ruleForm.createUserName" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="归档日期：" v-if="scene == 'update'">
        <el-input disabled style="width: 200px;" v-model="ruleForm.createTime" placeholder=""></el-input>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="onSubmit('ruleForm')">{{ scene == 'add' ? '新增' : '修改' }}</el-button>
        <el-button type="info" @click="$router.push('/Transfer/TransferList')">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 客户列表 -->
    <div class="dialogStyle">
      <el-dialog title="客户列表" :visible.sync="dialogShow" width="650px" :close-on-click-modal="false">
        <div style="display: flex;justify-content: space-around;">

          <el-input style="width: 150px;" type="text" v-model="userKeyphone" placeholder="用户手机号"></el-input>
          <el-input style="width: 150px;" type="text" v-model="userKeyname" placeholder="用户姓名"></el-input>
          <el-input style="width: 200px;" type="text" v-model="userKeyIdNumber" placeholder="用户身份证号"></el-input>
          <el-button type="primary" @click="searchForUser">搜索</el-button>
        </div>
        <span v-if="popUserData.length == 0" style="text-align: center;display: block;width: 100%;margin: 100px 0;">{{
          UserPopType == 'Old' ? '该房间未查到用户' : '请您输入搜索条件进行查询' }}</span>
        <el-table height="300" v-else :data="popUserData" style="width: 100%;margin-top: 20px;">
          <el-table-column prop="phone" label="手机号" width="180">
          </el-table-column>
          <el-table-column prop="customerName" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="idNumber" label="身份证号">
          </el-table-column>
          <el-table-column label="确认选择">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="ChangeUser(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import axios from 'axios'
import MyUploadImgNotDetele from '@/components/upload/MyUploadImgNotDetele'
import MyUploadFileNotDetele from '@/components/upload/MyUploadFileNotDetele'
import myCascader from '@/components/myCascader.vue'
export default {
  components: {
    MyUploadImgNotDetele,
    MyUploadFileNotDetele,
    myCascader
  },
  watch: {

  },
  data() {
    return {
      defaultVal: '',
      myCascaderShow: false,
      props: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad: async (node, resolve) => {
          console.log(node, '级联选择器');
          const { level } = node;
          if (level == 0) {
            let res = await this.$api.events.getCellList(
              {
                name: '',
                pageNum: 1,
                pageSize: 10000,
                roleIds: this.userData.roleIds
              })
            if (res.code == 200) {
              console.log(res.data.list, 'ahhh');
              resolve(res.data.list)

            } else {
              this.$message.error(res.message)
            }
          } else if (level == 1) {
            // 获取楼宇列表
            let res = await this.$api.events.getBuildingList({
              "residentialQuartersId": node.path[0]
            })
            if (res.code == 200) {
              res.data.list.push({
                name: '公共区域',
                id: 0,
                leaf: true
              })
              resolve(res.data.list)
            } else {
              this.$message.error(res.message)
            }
          } else if (level == 2) { //获取单元列表
            let res = await this.$api.axios.post('/business/room/getUnitCodeListByBuildingId', {
              "buildingId": node.path[1]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 3) { //获取楼层
            let res = await this.$api.axios.post('/business/room/getFloorsListByBuildingId', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 4) {
            let res = await this.$api.axios.post('/business/room/getRoomListByFloors', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2],
              "floors": node.path[3] //楼层  必填
            })
            if (res) {
              if (res.data.length > 0) {
                let arr = []
                res.data.forEach(el => {
                  arr.push({ ...el, leaf: true })
                })
                resolve(arr)
              } else {
                resolve([{
                  name: '暂无房间',
                  id: 0,
                  disabled: true,
                  leaf: true
                }])
              }

            }
          }else{
            resolve()
          }

        }
      },

      housesData: [],
      userData: {}, //登录用户信息
      scene: '',
      // 客户弹窗
      dialogShow: false,
      userKeyphone: '',
      userKeyname: '',
      userKeyIdNumber: '',
      popUserData: [],
      UserPopType: '', //Old原业主用户弹窗  New新业主用户弹窗

      keyValue: 0,//级联选择器key的渲染id
      options: [],//级联选择器回显的数据

      // 表单相关
      ruleForm: {
        customerOldOwner: {},
        customerNewOwner: {}
      },
      UserDataList: [],
      rules: {
        'customerOldOwner.roomIdsArray': [{ required: true, message: '请选择房间', trigger: 'change' }],
        'customerOldOwner.customerName': [{ required: true, message: '请选择客户', trigger: 'change' }],
        'customerOldOwner.phone': [
          { required: true, message: '请输入业主电话', trigger: 'blur' },
          // { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        'customerOldOwner.idNumber': [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          // { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号码格式不正确', trigger: 'blur' }
        ],
        'customerNewOwner.ownership': [{ required: true, message: '请选择房屋归属', trigger: 'change' }],
        'customerNewOwner.customerName': [{ required: true, message: '请选择业主姓名', trigger: 'change' }],
        'customerNewOwner.phone': [
          { required: true, message: '请输入业主电话', trigger: 'blur' },
          // { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        'customerNewOwner.idNumber': [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          // { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号码格式不正确', trigger: 'blur' }
        ],
      },
      //图片相关
      uploadId: 0, //图片和附件的上传
      EchoImgList: [],//要回显的图片
      deleteImg: [],//要删除的图片
      MyUploadImgNotDeteleShow: false,
      //附件
      EchoFileList: [],//要回显的附件
      deleteFile: [],//要删除的附件列表
      MyUploadFileNotDeteleShow: false,
    }
  },
  async activated() {
    let housesRes = await this.$api.customer.myGetOwnership()
    if (housesRes.code == 200) {
      this.housesData = housesRes.data
    } else {
      this.$message.error(housesRes.message)
    }

    this.scene = this.$route.query.scene //页面状态 新增还是修改
    this.userData = JSON.parse(sessionStorage.getItem('logOnUser')) //登录人信息
    this.editCascaderVisible = false //先让级联选择器关闭
    this.MyUploadImgNotDeteleShow = false
    this.MyUploadFileNotDeteleShow = false
    this.EchoImgList = [] //要回显的图片清空
    this.deleteImg = []  //把要删除的图片数组清空
    this.EchoFileList = [] //要回显的附件清空
    this.deleteFile = []  //把要删除的附件数组清空
    switch (this.scene) {
      case 'add':
        // 图片附件直接展示
        setTimeout(() => {
          this.MyUploadImgNotDeteleShow = true
          this.MyUploadFileNotDeteleShow = true
        }, 100)
        this.$set(this.ruleForm, 'createUserName', this.userData.name) //经办人回显

        //级联选择器相关 级联选择器相关
        this.myCascaderShow = false
        this.defaultVal = ''
        setTimeout(() => {
          this.myCascaderShow = true
        }, 50)
        // ================================	

        //清空数据
        this.uploadId = 0
        this.$set(this.ruleForm.customerOldOwner, 'roomIdsArray', [])
        this.$set(this.ruleForm.customerOldOwner, 'roomNamesArray', [])
        this.$set(this.ruleForm.customerOldOwner, 'customerId', '')
        this.$set(this.ruleForm.customerOldOwner, 'customerName', '')
        this.$set(this.ruleForm.customerOldOwner, 'phone', '')
        this.$set(this.ruleForm.customerOldOwner, 'idNumber', '')

        this.$set(this.ruleForm.customerNewOwner, 'ownership', '')
        this.$set(this.ruleForm.customerNewOwner, 'customerId', '')
        this.$set(this.ruleForm.customerNewOwner, 'customerName', '')
        this.$set(this.ruleForm.customerNewOwner, 'phone', '')
        this.$set(this.ruleForm.customerNewOwner, 'idNumber', '')

        this.$set(this.ruleForm, 'imagePaths', [])
        this.$set(this.ruleForm, 'annexPathArray', [])

        // ================================

        break
      case 'update':

        let res = await this.$api.customer.myGetTransferOwnershipDetail(this.$route.query.id)
        console.log(res, '详情数据');
        if (res.code != 200) {
          this.$message.error(res.message)
          return
        }
        let data = res.data
        // 处理原业主信息
        //级联选择器相关 级联选择器相关
        this.myCascaderShow = false
        this.defaultVal = data.customerOldOwner.roomNamesArray.join('/')
        setTimeout(() => {
          this.myCascaderShow = true
        }, 50)
        this.$set(this.ruleForm.customerOldOwner, 'id', data.customerOldOwner.id)
        this.$set(this.ruleForm.customerOldOwner, 'roomIdsArray', data.customerOldOwner.roomIdsArray)
        this.$set(this.ruleForm.customerOldOwner, 'roomNamesArray', data.customerOldOwner.roomNamesArray)
        this.$set(this.ruleForm.customerOldOwner, 'customerId', data.customerOldOwner.customerId)
        this.$set(this.ruleForm.customerOldOwner, 'customerName', data.customerOldOwner.customerName)
        this.$set(this.ruleForm.customerOldOwner, 'phone', data.customerOldOwner.phone)
        this.$set(this.ruleForm.customerOldOwner, 'idNumber', data.customerOldOwner.idNumber)

        // ================================

        //处理新业主信息
        this.$set(this.ruleForm.customerNewOwner, 'id', data.customerNewOwner.id)
        this.$set(this.ruleForm.customerNewOwner, 'ownership', data.customerNewOwner.ownership)
        this.$set(this.ruleForm.customerNewOwner, 'customerId', data.customerNewOwner.customerId)
        this.$set(this.ruleForm.customerNewOwner, 'customerName', data.customerNewOwner.customerName)
        this.$set(this.ruleForm.customerNewOwner, 'phone', data.customerNewOwner.phone)
        this.$set(this.ruleForm.customerNewOwner, 'idNumber', data.customerNewOwner.idNumber)
        // ================================



        // 处理回显 图片 附件
        this.uploadId = data.id
        if (data.imagePaths) {
          this.EchoImgList = data.imagePaths
          this.$set(this.ruleForm, 'imagePaths', data.imagePaths)
        } else {
          this.$set(this.ruleForm, 'imagePaths', [])
        }
        if (data.annexPathArray) {
          this.EchoFileList = data.annexPathArray
          this.$set(this.ruleForm, 'annexPathArray', data.annexPathArray)
        } else {
          this.$set(this.ruleForm, 'annexPathArray', [])
        }
        console.log(this.ruleForm.imagePaths,this.ruleForm.annexPathArray,'qocnd');
        setTimeout(() => {
          this.MyUploadImgNotDeteleShow = true
          this.MyUploadFileNotDeteleShow = true
        }, 100)
        // ================================

        // 经办人 归档日期
        this.$set(this.ruleForm, 'createUserName', data.createUserName)
        this.$set(this.ruleForm, 'createTime', data.createTime)
        break
    }
    this.$nextTick(() => {
      this.$refs.ruleForm.clearValidate()
    })
  },
  methods: {
    onSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$confirm('请检查信息无误后提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            //删除要删除的图片   
            if (this.deleteImg.length > 0) {
              this.deleteImg.forEach(async el => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/transferOwnership/deleteImg', {
                  "imageUrl": el
                })

              })
            }
            //删除要删除的附件  
            if (this.deleteFile.length > 0) {
              this.deleteImg.forEach(async el => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/transferOwnership/deleteAnnex', {
                  "filePath": el
                })

              })
            }
            switch (this.scene) {
              case 'add':
                {
                  let { imagePaths, annexPathArray, customerOldOwner, customerNewOwner, } = this.ruleForm
                  let params = {
                    imagePaths,
                    annexPathArray,
                    customerOldOwner,
                    customerNewOwner,
                    unitId: this.userData.unitId,
                    unitType: this.userData.unitType,
                  }
                  let addRes = await this.$api.customer.myTransferOwnershipInsert(params)
                  console.log(addRes, 'addRes');
                  if (addRes.code == 200) {
                    this.$message({
                      message: '新增成功',
                      type: 'success'
                    });
                    this.$router.push('/Transfer/TransferList')
                  } else {
                    this.$message.error(addRes.message)
                  }
                }
                break
              case 'update':
                {
                  console.log(this.ruleForm, '修改信息');
                  let { imagePaths, annexPathArray, customerOldOwner, customerNewOwner, } = this.ruleForm
                  let params = {
                    imagePaths,
                    annexPathArray,
                    customerOldOwner,
                    customerNewOwner,
                    id: this.$route.query.id,
                  }
                  let res = await this.$api.customer.myTransferOwnershipUpdate(params)
                  if (res.code == 200) {
                    this.$message({
                      message: '修改成功',
                      type: 'success'
                    });
                    this.$router.push('/Transfer/TransferList')
                  } else {
                    this.$message.error(res.message)
                  }
                }
                break
            }
          }).catch(() => {

          });
        }
      });
    },
    //========================================================选择用户 ↓
    choiceUser(val) {
      this.userKeyphone = ''
      this.userKeyname = ''
      this.userKeyIdNumber = ''
      this.UserPopType = val
      this.popUserData = []
      switch (val) {
        case 'Old':  //点击原业主选择
          if (this.ruleForm.customerOldOwner.roomIdsArray.length ==0) {
            this.$message.error('请先选择房间')
            return
          }
          this.searchForUser()
          break
        case 'New':  //点击新业主选择
          break
      }
      this.dialogShow = true
    },
    async searchForUser() { //搜索用户列表
      switch (this.UserPopType) {
        case 'Old':
          let res = await this.$api.customer.myGetBindingCustomerList({
            "roomId": this.ruleForm.customerOldOwner.roomIdsArray[this.ruleForm.customerOldOwner.roomIdsArray.length-1], //房间id 必填
            "name": this.userKeyname, //客户姓名
            "phoneNumber": this.userKeyphone, //客户手机号
            "idNumber": this.userKeyIdNumber //客户身份证号
          })
          if (res.code == 200) {
            this.popUserData = res.data
          } else {
            this.$message.error(res.message)
          }
          break
        case 'New':
          //必须先筛选 再查询
          if (!this.userKeyIdNumber && !this.userKeyname && !this.userKeyphone) {
            this.$message.error('请输入搜索条件进行查询')
            return
          }

          let res1 = await this.$api.customer.myGetCustomerList({
            "name": this.userKeyname, //客户姓名
            "phoneNumber": this.userKeyphone, //客户手机号
            "idNumber": this.userKeyIdNumber, //客户身份证号
            "pageSize": 10000,
            "pageNum": 1
          })
          if (res1.code == 200) {
            this.popUserData = res1.data.list
          } else {
            this.$message.error(res1.message)
          }
          break
      }
    },
    ChangeUser(val) { //弹窗的用户列表选择事件
      console.log(val, '弹窗的用户列表选择');
      switch (this.UserPopType) {
        case 'Old':
          this.$set(this.ruleForm.customerOldOwner, 'customerId', val.customerId)
          this.$set(this.ruleForm.customerOldOwner, 'customerName', val.customerName)
          this.$set(this.ruleForm.customerOldOwner, 'phone', val.phone)
          this.$set(this.ruleForm.customerOldOwner, 'idNumber', val.idNumber)
          break
        case 'New':
          this.$set(this.ruleForm.customerNewOwner, 'customerId', val.customerId)
          this.$set(this.ruleForm.customerNewOwner, 'customerName', val.customerName)
          this.$set(this.ruleForm.customerNewOwner, 'phone', val.phone)
          this.$set(this.ruleForm.customerNewOwner, 'idNumber', val.idNumber)
          break
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
      this.dialogShow = false
    },
    //========================================================选择用户 ↑


    //========================================================级联选择器 ↓
    myCascaderGetData(e) {
      console.log(e, '级联选择器的值')
      this.$set(this.ruleForm.customerOldOwner, 'customerId', '')
      this.$set(this.ruleForm.customerOldOwner, 'customerName', '')
      this.$set(this.ruleForm.customerOldOwner, 'phone', '')
      this.$set(this.ruleForm.customerOldOwner, 'idNumber', '')

      // 要替换的
      if (e.ids.length == 0) {
        this.$set(this.ruleForm.customerOldOwner, 'roomIdsArray', [])
        this.$set(this.ruleForm.customerOldOwner, 'roomNamesArray', [])
      } else {
        this.$set(this.ruleForm.customerOldOwner, 'roomIdsArray', [e.ids[0], e.ids[1], e.ids[4]])
        this.$set(this.ruleForm.customerOldOwner, 'roomNamesArray', [e.names[0], e.names[1], e.names[4]])
      }
      // 替换成的
      // this.$set(this.ruleForm.customerOldOwner, 'roomIdsArray', e.ids)
      // this.$set(this.ruleForm.customerOldOwner, 'roomNamesArray', e.names)

    },
    //========================================================级联选择器 ↑






    //========================================================图片和附件 ↓
    deleteImgList(val) { //删除图片的事件，点击保存再删除
      this.deleteImg.push(val)
    },
    deleteFileList(val) {//删除附件的事件，点击保存再删除
      this.deleteFile.push(val)
    },
    getImgList(val) { //图片列表
      this.ruleForm.imagePaths = val
    },
    getFileList(val) { //附件列表
      this.ruleForm.annexPathArray = val
    },
    //========================================================图片和附件 ↑
  },
}
</script>

<style lang="less" scoped>
.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}
</style>